﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebApp._console.page
{
    public partial class template_edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            _ctlHiddenName.Value = Request.QueryString["name"];

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                PageTemplate template = service.GetPageTemplate(_ctlHiddenName.Value);

                _ctlEditName.Text = template.Name;
                _ctlEditContent.Text = template.Content;
            }

            _ctlLinkBack.NavigateUrl = "./Template-list.aspx";
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();

            PageTemplate template = service.GetPageTemplate(_ctlHiddenName.Value);
            template.Content = _ctlEditContent.Text;

            if (service.SavePageTemplate(template))
            {
                StringBuilder builder = new StringBuilder();
                string s = Regex.Replace(template.Content, @"(?<prefix>[\\{]+)(?<name>[^\\{\\}]+)(?<suffix>[\\}]+)", "<asp:WebPartZone ID=\"${name}\" runat=\"server\"></asp:WebPartZone>", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
                s = s.Replace('[', '<').Replace(']', '>');


                builder.Append("<%@ Control Language=\"C#\" AutoEventWireup=\"true\" %>");
                builder.Append(s);

                System.IO.File.WriteAllText(Server.MapPath("~/_templates/_page/" + template.Name + ".ascx"), s);

                Response.Redirect(_ctlLinkBack.NavigateUrl);
            }
        }
    }
}